<template>
  <div class="content-box">
    <div class="content" v-loading="loading">
      <!-- 数据显示区域 -->
      <div class="data_place">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="查询时间" prop="dateRange">
            <el-date-picker
              :style="{
                width: device === 'mobile' ? '280px' : '355px',
                marginRight: '20px',
              }"
              clearable
              v-model="dateRange"
              type="daterange"
              :picker-options="pickerOptions"
              range-separator="至"
              value-format="yyyy-MM-dd"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- 图表显示区域 -->
      <div class="chart_place">
        <div
          :class="[
            'chart_item',
            device === 'desktop' ? 'oneEqualPartsPc' : 'oneEqualPartsMobile',
          ]"
          ref="inAndExpChart"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import * as echarts from "echarts";
import moment from "moment";

import { querySysInAndExpGraphList } from "@/api/inAndExpCount/sevenDaysinAndExp";
export default {
  name: "sevenDaysinAndExp",
  data() {
    return {
      // 查询参数
      queryParams: {},
      // 时间范围
      dateRange: [],
      loading: false,
      // 图标配置
      chartOptions: {
        title: {
          text: "7天收支柱状图",
          subtext: "一周内 数据",
          left: "left",
        },
        legend: {}, //显示图例
        tooltip: {
          // 悬停提示
        },
        dataset: {
          // 数据集
          source: [],
        },
        xAxis: { type: "category" }, // 适用于分类轴
        yAxis: {},
        series: [], // 控制图例显示，注第一个元素为字符按数组才会显示图例
      },
      // 数据映射对象
      dataMappObj: {
        billTime: {
          label: "统计日期",
          sort: 0,
        },
        upMoney: {
          label: "上游结算",
          sort: 1,
        },
        downMoney: {
          label: "下游结算",
          sort: 2,
        },
        sysMoney: {
          label: "毛利润",
          sort: 3,
        },
        changeMoney: {
          label: "修正金额",
          sort: 4,
        },
        lastMoney: {
          label: "最终毛利润",
          sort: 5,
        },
      },
      // 时间范围限制最大跨度为 7 天
      pickerOptions: {
        onPick: ({ minDate }) => {
          this.pickerMinDate = minDate;
        },
        disabledDate: (time) => {
          // 果当前判断的日期超过了第 7 天的结束时间，则禁用该日期。
          if (!this.pickerMinDate) return false;
          const start = moment(this.pickerMinDate);
          const end = moment(start).add(6, "days");
          return time.getTime() > end.endOf("day").valueOf();
        },
      },
      pickerMinDate: null,
    };
  },
  computed: {
    ...mapGetters(["device"]),
  },
  created() {
    this.init();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    // 初始化图表
    initChart() {
      // 客户状态图表实例初始化
      this.inAndExpChart = echarts.init(this.$refs.inAndExpChart);
      this.inAndExpChart.setOption(this.chartOptions);
      window.addEventListener("resize", this.resizeChart);
    },
    // 窗口缩放时重置图表
    resizeChart() {
      this.inAndExpChart && this.inAndExpChart.resize();
      // 如果是移动端不设置标题
      if (this.device === "mobile") {
        this.$set(this.chartOptions, "title", {});
      } else {
        this.$set(this.chartOptions, "title", {
          text: "7天收支柱状图",
          subtext: "一周内 数据",
          left: "left",
        });
      }
      // 强制更新图表配置
      this.inAndExpChart.setOption(this.chartOptions, true);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 完全重置到初始状态
      this.$set(this, "queryParams", {});
      this.init();
    },
    init() {
      // 设置默认时间
      this.$set(this, "dateRange", [
        moment().subtract(6, "days").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD"),
      ]);
      this.getList();
    },
    // 按照分类进行获取数据集
    getClassificatDataArray(dataList) {
      const newArr = dataList.reduce(
        (arr, item) => {
          for (const key in item) {
            if (this.dataMappObj[key]) {
              // 需要处理
              let i = this.dataMappObj[key].sort;
              if (arr[i]?.length == 0) {
                // 如果为空，第一个元素为文本信息
                arr[i].push(this.dataMappObj[key].label);
              }
              arr[i].push(item[key]);
            }
          }
          return arr;
        },
        Array.from({ length: Object.keys(this.dataMappObj).length }, () => [])
      );
      return newArr;
    },
    // 按照时间进行获取数据集
    getTimeDataArray(dataList) {
      // 图例列表
      let seriesArr = []; // 默认从1开始显示
      const newArr = dataList.map((pre) => {
        let arr = [];
        for (const key in pre) {
          if (this.dataMappObj[key]) {
            // 需要处理
            arr.splice(this.dataMappObj[key]?.sort, 1, pre[key]);
            // 处理series数组对应的图例文本
            seriesArr.splice(
              this.dataMappObj[key]?.sort,
              1,
              this.dataMappObj[key]?.label
            );
          }
        }
        return arr;
      });
      return [
        seriesArr, //默认从1开始显示
        ...newArr,
      ];
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      if (this.dateRange?.length) {
        this.queryParams.timeStart = this.dateRange[0];
        this.queryParams.timeEnd = this.dateRange[1];
      } else {
        delete this.queryParams.timeStart;
        delete this.queryParams.timeEnd;
      }
      querySysInAndExpGraphList(this.queryParams).then((res) => {
        if (res.code == 200) {
          let sourceList = this.getTimeDataArray(res?.data);
          // 处理数据集
          this.$set(this.chartOptions.dataset, "source", sourceList);
          // 处理显示tab项
          this.$set(
            this.chartOptions,
            "series",
            Array.from(
              { length: Object.keys(this.dataMappObj)?.length - 1 },
              () => ({
                type: "bar",
                barMinHeight: 1,
                label: {
                  show: true, // 显示标签
                  position: "top", // 标签位置（可选 top/bottom/left/right/inside/...）
                  valueAnimation: true, // 动画显示数值变化
                },
              })
            )
          );
          console.log(this.chartOptions);
          // 如果是移动端不设置标题
          if (this.device === "mobile") {
            this.$set(this.chartOptions, "title", {});
          } else {
            this.$set(this.chartOptions, "title", {
              text: "7天收支柱状图",
              subtext: "一周内 数据",
              left: "left",
            });
          }
          // 强制更新图表配置
          this.inAndExpChart.setOption(this.chartOptions, true);
        }
        this.loading = false;
      }).catch((err) => {
        setTimeout(() => {// 延迟2s后自动取消加载状态
          this.loading = false;
        }, 2000);
      })
    },
  },
};
</script>

<style scoped lang='scss'>
.content {
  background-color: #fff;
  // height: 100%;
  padding: 20px;
  border-radius: 6px;
  .data_place {
    padding-bottom: 20px;
    border-bottom: 1px solid #efefef;
  }
  .chart_place {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding-top: 20px;
    .chart_item {
      box-shadow: 0 4px 6px #d1cfcf;
      filter: drop-shadow(0px 0px 3px #d0d0d0);
      border-radius: 6px;

      flex: 1 1 100%; // 每个子盒子占 100% 的宽度，最多 1 个子盒子一行
      max-width: 100%; // 最大宽度为 100%
    }
    // 一等分PC样式
    .oneEqualPartsPc {
      height: calc(100vh - 270px);
    }
    // 一等分移动端样式
    .oneEqualPartsMobile {
      height: 400px;
    }
  }
}
.textBlue {
  color: #1890ff;
}
</style>